<template>
  <div class="device-request-container">
    <h2>设备使用申请</h2>
    
    <!-- 申请表单 -->
    <el-card class="request-card">
      <el-form :model="requestForm" :rules="rules" ref="requestFormRef" label-width="100px">
        <el-form-item label="设备" prop="deviceId">
          <el-select 
            v-model="requestForm.deviceId" 
            placeholder="请选择设备" 
            style="width: 100%"
            filterable
          >
            <el-option 
              v-for="device in deviceList" 
              :key="device.id" 
              :label="`${device.deviceName} (${device.model})`" 
              :value="device.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用时间" prop="useTime">
          <el-date-picker
            v-model="requestForm.useTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="使用目的" prop="purpose">
          <el-input v-model="requestForm.purpose" type="textarea" rows="3" placeholder="请简要说明使用目的" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRequest">提交申请</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 申请历史 -->
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>申请历史</span>
        </div>
      </template>
      <el-table :data="requestHistory" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="申请编号" width="120" />
        <el-table-column label="设备" width="200">
          <template #default="{ row }">
            {{ getDeviceName(row.deviceId) }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { list as listDevices } from '@/api/device'
import { list as listApplyRequests, add } from '@/api/applyrequest'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const requestFormRef = ref(null)
const loading = ref(false)
const deviceList = ref([])
const deviceMap = ref({})

const requestForm = reactive({
  deviceId: '',
  useTime: [],
  purpose: ''
})

const rules = {
  deviceId: [{ required: true, message: '请选择设备', trigger: 'change' }],
  useTime: [{ required: true, message: '请选择使用时间', trigger: 'change' }],
  purpose: [{ required: true, message: '请输入使用目的', trigger: 'blur' }]
}

const requestHistory = ref([])

const statusMap = {
  0: { text: '待审批', type: 'warning' },
  1: { text: '已通过', type: 'success' },
  2: { text: '已驳回', type: 'danger' }
}

const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

const getDeviceName = (deviceId) => {
  return deviceMap.value[deviceId]?.deviceName || '未知设备'
}

const fetchDevices = async () => {
  try {
    const res = await listDevices()
    deviceList.value = res
    deviceMap.value = res.reduce((map, device) => {
      console.log(res)
      map[device.id] = device
      return map
    }, {})
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

const fetchRequestHistory = async () => {
  loading.value = true
  try {
    const res = await listApplyRequests({ userId: userStore.userId })
    requestHistory.value = res
  } catch (error) {
    console.error('获取申请历史失败:', error)
    ElMessage.error('获取申请历史失败')
  } finally {
    loading.value = false
  }
}

const submitRequest = async () => {
  if (!requestFormRef.value) return
  
  try {
    await requestFormRef.value.validate()
    
    const formData = {
      deviceId: requestForm.deviceId,
      startTime: requestForm.useTime[0],
      endTime: requestForm.useTime[1],
      purpose: requestForm.purpose,
      userId: userStore.userId
    }
    
    await add(formData)
    ElMessage.success('申请提交成功')
    
    // 重置表单
    requestFormRef.value.resetFields()
    
    // 刷新申请历史
    await fetchRequestHistory()
  } catch (error) {
    if (error.message !== 'validate') {
      console.error('提交申请失败:', error)
      ElMessage.error('提交申请失败')
    }
  }
}

onMounted(() => {
  fetchDevices()
  fetchRequestHistory()
})
</script>

<style scoped>
.device-request-container {
  padding: 20px;
}

.request-card {
  margin-bottom: 20px;
  max-width: 800px;
}

.history-card {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>